from django.http              import Http404
from django.shortcuts         import render_to_response
from django.template          import RequestContext
from sitepal.sitemenu.actions import SimpleView,ACTION_EXECUTE_VIEW
from sitepal.sitemenu.models  import MenuView
from sitepal.sitetheme.models import Theme

def serve_content(request,path):
    match = MenuView.objects.resolve_path(path)
    if match:
        view,args,kwargs  = match
        request.menu_path = path
        request.menu_view = view
        return view.callback(request,*args,**kwargs)
    else:
        raise Http404

def admin_handler(request,view):
    def map_menu_link(link):
        return (link.title,link.view.description or u' ')
    menu_links = MenuView.objects.get_children_links_for_path(request.menu_path,request.user)
    menu_view  = request.menu_view
    header     = (u'Name',u'Description')
    bodies     = (map(map_menu_link,menu_links),)
    theme      = Theme.objects.get_current()
    content    = theme.render_table(bodies,menu_view.title,header,empty=u'No entries',
                                    request=request)
    return view.response(request,view.get_context(request,content))
    

admin = SimpleView(
    template_name        = 'themes/current/page.html',
    template_object_name = 'content',
    action_handler       = admin_handler,
    http_methods         = 'GET',
    permissions          = { ACTION_EXECUTE_VIEW: 'sitemenu.call_menuview' }
)

def menu_list_handler(request,view):
    content = u"Hello World!"
    return view.response(request,view.get_context(request,content))

menu_list = SimpleView(
    template_name        = 'themes/current/page.html',
    template_object_name = 'content',
    action_handler       = menu_list_handler,
    http_methods         = 'GET',
    permissions          = { ACTION_EXECUTE_VIEW: 'sitemenu.call_menuview' }
)

